
import axios from 'axios';

export async function downloadByUrl({
    url,
    params,
    data,
    fileName,
}) {
    try {
        const res = await axios.post(url, data, {
            params: params,
            responseType: 'blob' // 确保响应类型是 Blob
        });

        let name = res.headers['content-disposition'];
        if (name === undefined) {
            downloadByData(res.data, fileName);
        } else {
            const matches = name.match(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/);
            if (matches && matches[1]) {
                const nameDecoded = matches[1].replace(/utf-8'zh_cn'|['"]/g, '');
                const decodedFileName = decodeURIComponent(nameDecoded.trim()) || fileName || 'jeesite';
                downloadByData(res.data, decodedFileName);
            } else {
                downloadByData(res.data, fileName || 'jeesite');
            }
        }
    } catch (error) {
        console.error('Error downloading the file:', error);
        return false;
    }

    return true;
}

export function downloadByData(data, filename, mime, bom) {
    const blobData = typeof bom !== 'undefined' ? [bom, data] : [data];
    const blob = new Blob(blobData, { type: mime || 'application/octet-stream' });
    if (typeof window.navigator.msSaveBlob !== 'undefined') {
        window.navigator.msSaveBlob(blob, filename);
    } else {
        const blobURL = window.URL.createObjectURL(blob);
        const tempLink = document.createElement('a');
        tempLink.style.display = 'none';
        tempLink.href = blobURL;
        tempLink.setAttribute('download', filename);
        if (typeof tempLink.download === 'undefined') {
            tempLink.setAttribute('target', '_blank');
        }
        document.body.appendChild(tempLink);
        tempLink.click();
        document.body.removeChild(tempLink);
        window.URL.revokeObjectURL(blobURL);
    }
}